package com.sptpc.demo1.controller;

import com.sptpc.demo1.model.Category;
import com.sptpc.demo1.model.Drink;
import com.sptpc.demo1.service.ICategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/category")
public class CategoryControoller {
    @Autowired
    public ICategoryService categoryService;

    @GetMapping("/")
    public List<Category> getAll(){

        return categoryService.getAllCategory();

    }
    @PutMapping("/")
    public Category modifyDrink(@RequestBody Category request) {
        log.info("修改分类: {}", request);
        //看看有无产品
        Category category = categoryService.getAllCategoryById(Math.toIntExact(request.getId()));
        //2.把要修改的内容-》drin 对应属性
        BeanUtils.copyProperties(request,category);
        //更新
        categoryService.updateDrink(category);
        return category;
    }
    //添加
//   新增
//    post /drink/ {"name":"奶茶","price":"8.0"}
//    传参思路
//    直接使用实体类 Valid数据校验
    @PostMapping("/")
    public Category addNewDrink(@RequestBody Category category,
                                BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            for (ObjectError error : bindingResult.getAllErrors()) {
                log.error(error.toString());
            }
            return null;//给前端返回空值
        } else {
            log.info("新增饮品分类：{}", category);
            categoryService.addNewDrink(category);
            return category;
        }

    }
    @DeleteMapping("/{id}")
    public String deleteDrink(@PathVariable Integer id){
        log.info("删除饮品分类: {}",id);
        categoryService.deleteDrinkById(id);
        return "删除成功";

    }





}


